package com.asinking.com.openapi.sdk.entity;



import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.asinking.com.openapi.sdk.core.HttpMethod;
import com.asinking.com.openapi.sdk.core.HttpRequest;
import com.asinking.com.openapi.sdk.core.HttpResponse;
import com.asinking.com.openapi.sdk.okhttp.AKRestClientBuild;
import com.asinking.com.openapi.sdk.okhttp.HttpExecutor;
import com.asinking.com.openapi.sdk.sign.ApiSign;
import com.yonyou.iuap.ipaas.cache.core.CacheService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @Title:
 * @Description: TODO 调用领星接口公共方法
 * @Author: zs
 * @DateTime: 2024/10/17 15:36
 */
public class LxRequestEntity {

    public static final CacheService cacheService = CacheService.getCacheService();

    private String appKey;//ak_iV1JZM1CSqWQa
    private String appSecret;///OP15GJNTpxBq6t/nrjoCQ==
    private String endpoint;//https://openapi.lingxing.com 领星接口地址
    private final Long time = 7200L;

    public void WangdianerpueConnection(String appKey, String appSecret, String endpoint) {
        this.appKey = appKey;
        this.appSecret = appSecret;
        this.endpoint = endpoint;
    }

    public JSONObject doPost(String path, Map<String, Object> body) throws Exception{
        // 基本请求参数
        Map<String, Object> queryParam = new HashMap<>();
        queryParam.put("timestamp", System.currentTimeMillis() / 1000 + "");
        queryParam.put("app_key", appKey);
        queryParam.put("access_token", getLxToken(appKey,appSecret,endpoint));
        MapListToStr(body, queryParam);

        String sign = ApiSign.lxSign(queryParam, appKey);
        queryParam.put("sign", sign);

        HttpRequest<Object> build = HttpRequest.builder(Object.class)
                .method(HttpMethod.POST)
                .endpoint(endpoint)
                .path(path)
                .queryParams(queryParam)
                .json(JSONUtil.toJsonStr(body))
                .build();
        HttpResponse execute = HttpExecutor.create().execute(build);
        return execute.readEntity(JSONObject.class);
    }

    private void MapListToStr(Map<String, Object> body, Map<String, Object> queryParam) {
        for (String key : body.keySet()) {
            if (body.get(key) instanceof List || body.get(key) instanceof ArrayList || body.get(key) instanceof JSONArray){
                queryParam.put(key, JSONUtil.toJsonStr(body.get(key)));
            }else {
                queryParam.put(key,body.get(key));
            }
        }
    }


    public JSONObject LXGet(String path, Map<String, Object> queryParam) throws Exception {
        MapListToStr(queryParam, queryParam);
        queryParam.put("timestamp", System.currentTimeMillis() / 1000 + "");
        queryParam.put("access_token", getLxToken(appKey,appSecret,endpoint));
        queryParam.put("app_key", appKey);
        String sign = ApiSign.lxSign(queryParam, appKey);
        queryParam.put("sign", sign);
        HttpRequest<Object> build = HttpRequest.builder(Object.class)
                .method(HttpMethod.GET)
                .endpoint(endpoint)
                .path(path)
                .queryParams(queryParam)
                .build();
        HttpResponse execute = HttpExecutor.create().execute(build);
        return execute.readEntity(JSONObject.class);
    }





    public String getLxToken(String appKey,String appSecret,String endpoint) throws Exception {
        String cacheKey = "token:" + appKey;
        String access_tokenKey = "access_token" ;
        String refresh_tokenKey = "refresh_token" ;
        String token = "";
        Object cacheValue = cacheService.get(cacheKey);
        if (cacheValue == null) {
            Result result = AKRestClientBuild.builder().endpoint(endpoint).getAccessToken(appKey, appSecret);
            Map<String, Object> resultData = (Map<String, Object>) result.getData();
            token = (String)resultData.get(access_tokenKey);
            cacheService.put(cacheKey, resultData.get(access_tokenKey)+"@"+resultData.get(refresh_tokenKey)+"@"+System.currentTimeMillis(), time);
//            cacheService.put(refresh_tokenKey, resultData.get(refresh_tokenKey), time);
        } else {
            String[] cacheValueArr = Convert.toStr(cacheValue).split("@");
            String accessToken = cacheValueArr[0];
            String refreshToken = cacheValueArr[1];
            // 当前时间戳-缓存刚存进去的时间戳 为 访问令牌已消耗的过期时间
            long startTimeMillis = System.currentTimeMillis() - Long.parseLong(cacheValueArr[2]);
            if (startTimeMillis < 1800*1000) {
                // 如果用postman等其他工具调试时，需要将appSecret用urlencode.encode()进行转义
                Map<String, Object> resultRefreshData = (Map<String, Object>)AKRestClientBuild.builder().endpoint(endpoint).refreshToken(appKey, refreshToken);
                Map<String, Object> resultRefresh =(Map<String, Object>)resultRefreshData.get("data");
                token = (String)resultRefresh.get(access_tokenKey);
                cacheService.put(cacheKey, resultRefresh.get(access_tokenKey)+"@"+resultRefresh.get(refresh_tokenKey)+"@"+System.currentTimeMillis(), time);
//                cacheService.put(refresh_tokenKey, resultRefresh.get(refresh_tokenKey), time);
            } else {
                token = accessToken;
            }
        }
        return token;
    }

}
